import type Uppy from '@uppy/core';
import { Dialog, DialogContent, DialogFooter, DialogTitle } from '../ui/Dialog';
import { useMemo, useState } from 'react';
import { useUppyState } from '@/app/dashboard/useUppyState';
import { Button } from '../ui/Button';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { LocalFileItem } from './FileItem';

export function UploadPreview({ uppy }: { uppy: Uppy }) {
  const files = useUppyState(uppy, (state) => Object.values(state.files));

  const hasNotUploadedFile = useMemo(() => {
    return files.length > 0;
  }, [files]);

  const [isUploading, setIsUploading] = useState(false);
  const [index, setIndex] = useState(0);
  const file = files[index];

  const clear = () => {
    uppy.removeFiles(files.map(({ id }) => id));
    setIndex(0);
  };

  return file ? (
    <Dialog
      open={hasNotUploadedFile}
      onOpenChange={(flag) => {
        if (flag === false) {
          clear();
        }
      }}
    >
      <DialogContent onPointerDownOutside={(e) => e.preventDefault()}>
        <DialogTitle>Upload Preview</DialogTitle>
        <div className="flex items-center justify-between">
          <Button
            onClick={() => {
              setIndex((idx) => {
                return idx === 0 ? files.length - 1 : idx - 1;
              });
            }}
            variant="ghost"
          >
            <ChevronLeft />
          </Button>
          <div className="w-56 h-56 flex justify-center items-center">
            <LocalFileItem file={file.data as File} />
          </div>
          <Button
            variant="ghost"
            onClick={() => {
              setIndex((idx) => {
                return idx === files.length - 1 ? 0 : idx + 1;
              });
            }}
          >
            <ChevronRight />
          </Button>
        </div>
        <DialogFooter>
          <Button
            onClick={() => {
              uppy.removeFile(file.id);
              if (index === files.length - 1) {
                setIndex((idx) => (idx - 1 >= 0 ? idx - 1 : 0));
              }
            }}
            variant="destructive"
          >
            Delete This
          </Button>
          <Button
            onClick={() => {
              setIsUploading(true);
              uppy.upload().then(() => {
                setIsUploading(false);
                clear();
              });
            }}
            disabled={isUploading}
          >
            Upload All
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  ) : null;
}
